package com.card.server.service.impl;

import com.card.server.config.RedisService;
import com.card.server.domain.MatchUser;
import com.card.server.domain.R;
import com.card.server.domain.UserEmitters;
import com.card.server.mapper.UserGameLogMapper;
import com.card.server.model.entity.UserGameLog;
import com.card.server.model.ro.UserInfo;
import com.card.server.service.IMatchService;
import com.card.server.utils.JsonUtils;
import com.card.server.utils.MatchUtil;
import com.fasterxml.jackson.databind.deser.DataFormatReaders;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import reactor.core.publisher.FluxSink;

import java.util.*;


/**
 * @author TISNIW
 * @version 1.0
 * @date 2025/5/26 8:19
 * @desc
 */
@Service
public class MatchServiceImpl implements IMatchService {
    private static final String USER_INFO_KEY = "user:info:";
    private static final Logger log = LoggerFactory.getLogger(MatchServiceImpl.class);
    @Autowired
    private RedisService redisService;
    private static final String MATCH_QUERY_KEY = "match:query:";

    @Autowired
    private UserGameLogMapper userGameLogMapper;
    @Autowired
    private MatchUtil matchUtil;

    @Override
    public R<String> join(String userId,Integer game,Integer table) {
        Integer.valueOf(userId);
        UserInfo userInfo = null;
        String userInfoKey = USER_INFO_KEY + userId + ":";
        log.info("userId-{}",userInfoKey);
        if (redisService.hasKey(userInfoKey)) {
            //从缓存中获取用户信息
            String userJson = redisService.getCacheObject(userInfoKey, String.class);
            if (userJson != null) {
                Map<String, Object> userData = JsonUtils.parseObject(userJson, Map.class);
                userInfo = new UserInfo();
                userInfo.setId(Integer.valueOf(userData.get("id").toString()) );
                userInfo.setUsername(userData.get("username").toString() );
                userInfo.setAvatar(userData.get("avatar").toString());
                userInfo.setToken(userData.get("token").toString());
                userInfo.setAccount(userData.get("account").toString());
                userInfo.setLevel(Integer.valueOf(userData.get("level").toString()));
                userInfo.setExp(Integer.valueOf(userData.get("exp").toString()));
                userInfo.setChip(Integer.valueOf(userData.get("chip").toString()));
            }
        }
        if (userInfo == null){
            return R.fail(300,"用户信息不存在");
        }
        //获取用户胜率
        UserGameLog gameLog = userGameLogMapper.queryById(userInfo.getId());

        Double winRate = Double.valueOf(gameLog.getWin())/(Double.valueOf(gameLog.getWin())+Double.valueOf(gameLog.getLose()));
        log.info("用户总获胜场数{},失败场数{}",gameLog.getWin(),gameLog.getLose());
        String key = buildPoolKey(game,table) +
                userId+":"+
                userInfo.getLevel();
        MatchUser match = new MatchUser();
        match.setId(userInfo.getId());
        match.setOriginalLevel(userInfo.getLevel());
        match.setChip(userInfo.getChip());
        match.setGameType(game);
        match.setTableType(table);
        match.setWinRate(winRate);
        match.setWinCount(gameLog.getWinCount());
        match.setLoseCount(gameLog.getLoseCount());
        //获取当前时间
        match.setJoinTime(new Date());
        redisService.setCacheObject(key, match);
        return R.ok("已加入匹配队列");
    }
    @Scheduled(fixedRate = 1000)
    public void checkMatchingUsers() {
        matchUtil.checkMatchingUsers();
//        List<MatchUser> query = new ArrayList<>();
//        for (int game = 1; game <= 1; game++) { // 假设有3种游戏类型
//            for (int table = 1; table <= 4; table++) { // 假设有4种桌子类型
//                String poolKey = buildPoolKey(game, table);
//                Set<String> keys = redisService.getKeysByPattern(poolKey + "*");
//
//                if (keys != null && !keys.isEmpty()) {
//                    for (String key : keys) {
//                        MatchUser matchUser = redisService.getCacheObject(key, MatchUser.class);
//                        if (matchUser != null) {
//                            log.info("匹配用户信息：{}", matchUser);
//                            query.add(matchUser);
//                        }
//                    }
//                }
//            }
//        }
//        log.info("正在匹配用户数量{}", query.size());
//        for (MatchUser matchUser : query) {
//            String userIdStr = String.valueOf(matchUser.getId());
//            FluxSink<String> emitter = UserEmitters.userEmitters.get(userIdStr);
//
//            if (emitter != null && !emitter.isCancelled()) {
//                Map<String, Object> response = new HashMap<>();
//                response.put("status", "matching");
//                response.put("message", "正在为您寻找对手...");
//                response.put("timestamp", System.currentTimeMillis());
//
//                emitter.next(JsonUtils.writeValueAsString(response));
//
//                // redisService.deleteObject(buildPoolKey(matchUser.getGameType(), matchUser.getTableType()) + ... );
//                // UserEmitters.userEmitters.remove(userIdStr);
//            }
//        }
    }
    @PostConstruct
    public void init() {
        log.info("项目启动时立即检查匹配队列...");
        checkMatchingUsers(); // 在项目启动时立即执行一次
    }
    public String buildPoolKey(Integer game, Integer table) {
        return MATCH_QUERY_KEY + game + ":" + table + ":";
    }
}
